package edu.gdkm.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return HandlerInterceptor.super.preHandle(request, response, handler);
        if(request.getSession().getAttribute("username")!=null){
            return true;
        }else {
            request.setAttribute("msg","你没有权利，请登录后重试");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ModelMap models= modelAndView.getModelMap();
        for(String key : models.keySet()){
            if(!key.contains("springframework")){
                ObjectMapper om =new ObjectMapper();
                String value=om.writeValueAsString(models.get(key));

                value=value.replaceAll("清","*");
                Object o =om.readValue(value,models.get(key).getClass());
                modelAndView.getModel().put(key,o);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("----------------------------");
        System.out.println("interceptor afterCompletion");
        System.out.println(ex);
        System.out.println("----------------------------");
    }
}
